<template>
  <div class="evaluation-results">
    <div class="header">
      <el-icon class="back-icon" @click="router.back()">
        <ArrowLeft />
      </el-icon>
      <span class="title">所有用户测评报告</span>
    </div>
    <div class="results-list" v-loading="isLoading">
      <div v-if="evaluationResults.length === 0" class="empty-state">
        暂无测评结果
      </div>
      <div v-else class="result-items">
        <div
          v-for="result in evaluationResults"
          :key="result.id"
          class="result-item"
          @click="showDetail(result.id)"
        >
          <div class="result-content">
            <div class="result-title">{{ result.questionnaire?.title }}</div>
            <div class="result-score">得分：{{ result.total_score }}</div>
            <div class="result-user">用户：{{ result.user?.name || result.user?.username || '未知' }}</div>
            <div class="result-time">{{ formatTime(result.created_at) }}</div>
          </div>
          <el-icon class="arrow-icon"><ArrowRight /></el-icon>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue'
import { Api } from '@/api'
import dayjs from 'dayjs'
import { useUserStore } from '@/stores/user.js'

const router = useRouter()
const userStore = useUserStore()
const evaluationResults = ref([])
const isLoading = ref(false)

// 仅允许咨询师访问
if (!userStore.user?.is_counselor) {
  router.replace('/profile')
}

const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

const fetchResults = async () => {
  isLoading.value = true
  try {
    // 1. 获取所有预约
    const appointmentsRes = await Api.getAllAppointments()
    if (appointmentsRes.data.status !== 200) throw new Error('获取预约失败')
    const myId = userStore.user?.id
    const appointments = appointmentsRes.data.data.appointments || []
    console.log('appointments:', appointments)
    console.log('myId:', myId)
    // 2. 筛选counselor_id等于自己id的预约，提取user_id
    const userIds = Array.from(new Set(
      appointments
        .filter(a => String(a.counselor_id) === String(myId))
        .map(a => a.user_id)
        .filter(Boolean)
    ))
    console.log('userIds:', userIds)
    // 3. 并发获取每个user_id的测评报告
    const reportPromises = userIds.map(user_id =>
      Api.getUserPsychologyReports({ user_id })
        .then(res => {
          console.log('user_id:', user_id, 'reportRes:', res.data)
          return (res.data.status === 200 && Array.isArray(res.data.data)) ? res.data.data : []
        })
        .catch((e) => { console.log('user_id:', user_id, 'error:', e); return [] })
    )
    const allReportsArr = await Promise.all(reportPromises)
    console.log('allReportsArr:', allReportsArr)
    // 合并所有报告并去重（按id）
    const allReports = [].concat(...allReportsArr)
    const uniqueReports = []
    const seen = new Set()
    for (const report of allReports) {
      if (report && !seen.has(report.id)) {
        uniqueReports.push(report)
        seen.add(report.id)
      }
    }
    console.log('evaluationResults:', uniqueReports)
    evaluationResults.value = uniqueReports
  } catch (error) {
    console.error('获取测评结果失败:', error)
    ElMessage.error('获取测评结果失败，请稍后再试')
  } finally {
    isLoading.value = false
  }
}

const showDetail = (id) => {
  router.push(`/profile/evaluation/${id}`)
}

onMounted(() => {
  fetchResults()
})
</script>

<style scoped>
.evaluation-results {
  background-color: #f7f8fa;
  min-height: 100vh;
}
.header {
  display: flex;
  align-items: center;
  padding: 10px 16px;
  background-color: white;
  border-bottom: 1px solid #f0f0f0;
}
.back-icon {
  font-size: 20px;
  cursor: pointer;
  margin-right: 16px;
}
.title {
  font-size: 16px;
  font-weight: 500;
}
.results-list {
  margin-top: 10px;
}
.empty-state {
  text-align: center;
  padding: 40px;
  color: #999;
  background-color: white;
}
.result-items {
  background-color: white;
}
.result-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
}
.result-item:active {
  background-color: #f7f8fa;
}
.result-content {
  flex: 1;
}
.result-title {
  font-size: 16px;
  color: #333;
  margin-bottom: 8px;
}
.result-score {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
}
.result-user {
  font-size: 13px;
  color: #888;
  margin-bottom: 4px;
}
.result-time {
  font-size: 12px;
  color: #999;
}
.arrow-icon {
  color: #999;
  font-size: 16px;
  margin-left: 8px;
}
</style>
